<template>
  <div>
    <a-form style="max-width: 80%; margin: 40px auto 0;">
      <a-alert
        :closable="true"
        message="请确认存在问题记录的表格！默认有问题记录的 Excel 表格不会选中导入！但允许选中强行导入！"
        style="margin-bottom: 24px;"
      />
      <a-form-item>
        <a-card>
          <a-checkbox-group v-model:value="selectedItems" style="width: 100%">
            <a-row v-for="(value, key) in checkResult">
              <a-col :span="10">
                <a-checkbox :value="key"><span :class="{'my-warning': value.length>0}">{{setLabel(key,value)}}</span></a-checkbox>
              </a-col>
              <a-col :span="4">
                  <a-select style="width: 8vw"
                            allowClear
                            show-search
                            placeholder="上游客户"
                            :filter-option="false"
                            @search="(v) => queryParams.searchText[key]=v"
                            :options="customizedFilterOptions(queryParams.searchText[key], traders)"
                            dropdownClassName="custom-dropdown"
                            v-model:value="queryParams.id_client[key]">
                    >
                </a-select>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-card>
      </a-form-item>
      <a-form-item :wrapperCol="{span: 19, offset: 5}">
        <a-row :gutter="16">
          <a-col :offset="6" :span="8">
            <a-checkbox v-model:checked="selectAll" @change="handleSelectAll">忽略问题，全选</a-checkbox>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :offset="5" :span="2">
            <a-button style="margin-left: 8px" @click="prevStep">上一步</a-button>
          </a-col>
          <a-col :offset="1" :span="8">
            <a-button :loading="loading" type="primary" @click="save">导入</a-button>
          </a-col>
        </a-row>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import { deleteAction, downFile, getAction, postAction, postDownFile } from '@/utils/request.js';
import useUserStore from '@/store/modules/user'
import {customizedFilterOptions} from "@/utils/my.js";

// dict
const currentUser = useUserStore()

// 定义 props
const props = defineProps(['checkData', 'checkResult', 'traders']);
// 定义 emits
const emit = defineEmits(['nextStep', 'prevStep']);

// 响应式数据
const loading = ref(false)
const selectedItems = ref([]);
const selectAll = ref(false);
const queryParams = ref({
  id_client: {},
  searchText: {}
});
const url = {
  import_from_excel_data: '/yg/import_from_excel_data'
}

// 监听 selectAll 变化
watchEffect(() => {
  console.log('Auto-processing Excel check results...')
  // Clear previous values
  selectedItems.value = []
  // Reactively depends on props.checkResult
  for (const k in props.checkResult) {
      if (props.checkResult[k].length === 0) {
        selectedItems.value.push(k)
      }
  }
})
selectAll.value = selectedItems.value.length === Object.keys(props.checkResult).length
// 方法
const setLabel = (key, value) => {
  if (value.length > 0) {
    return `${key}（存在问题记录${value.length}票）`;
  }
  return key;
};

const save = async () => {
  if (selectedItems.value.length === 0) {
    message.warning('没有要导入的数据！');
    return;
  }
  const data = {};
  for (const k in props.checkData) {
    if (selectedItems.value.includes(k)) {
      if (!queryParams.value.id_client[k]) {
        message.error(`${k}，上游公司不能为空！`);
        return;
      }
      data[k] = [props.checkData[k], queryParams.value.id_client[k]];
    }
  }
  try {
    loading.value = true
    const res = await postAction(url.import_from_excel_data, {
      records: data,
      create_by: currentUser.name
    });
    //loading.value = false
    if (!res || !res.success) {
      message.warning('保存失败！');
      return;
    }
    nextStep();
  } catch (error) {
    message.warning('保存失败！');
  }
};

const nextStep = () => {
  setTimeout(() => {
    emit('nextStep');
  }, 1500);
};

const prevStep = () => {
  emit('prevStep');
};

const handleSelectAll = (checkedValue) => {
    if (selectAll.value)
        selectedItems.value = Object.assign({}, Object.keys(props.checkResult))
    else
        selectedItems.value.splice(0, selectedItems.value.length)
}
</script>

<style scoped>
.my-warning {
  background-color: #f66c4b;
}
</style>